package com.hmyd.hmyd_android.shop;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.JfMallAddressAdapter;
import com.hmyd.hmyd_android.adapter.JfMallAddressAdapter.AdapterNetRequest;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Address;
import com.hmyd.hmyd_android.dto.DtoInfo;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.Info;
import com.hmyd.hmyd_android.ui.BasicListActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 积分商城地址管理
 * @author wangk
 */

@ContentView(R.layout.activity_jf_mall_adres)
public class JfMallAdresActivity extends BasicListActivity implements
		OnItemClickListener {

	private static final int GET_ADDRESS_LIST = 1201; // 获取地址列表
	private static final int SET_DEFAULT_ADDESS = 1202; // 将地址设为默认
	private static final int DELETE_ADDRESSS = 1203; // 删除地址
	
	private static final int ADDRESS_ADD_VIEW_ID = 9876;

	@ViewInject(R.id.addList)
	private XListView addressList; // 地址list
	@ViewInject(R.id.address_title)
	private View address_title;
	@ViewInject(R.id.home_title_txt)
	private TextView home_title_txt;
	@ViewInject(R.id.home_right)
	private TextView home_right;

	private JfMallAddressAdapter mJfMallAddressAdapter;
	private List<Address> datas;
	private Address defaultAddress;

	private Editor editor;
	private SharedPreferences sharedPreferences;

	private AdapterNetRequest adapterNetRequest;

	private int starter;

	private final int IS_FROM_SHOP_CART = 1;

	private String deleteId;
	
	private LinearLayout footView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	public XListView getXList() {
		return addressList;
	}

	private OnClickListener clickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case ADDRESS_ADD_VIEW_ID:
				if(datas.size()>=5) {
					MyToast.showHMToast(JfMallAdresActivity.this, false, "地址添加上限为5个，不能继续添加");
					return;
				}
				Intent intent = new Intent();
				intent.setClass(JfMallAdresActivity.this,
						JfMallAddNewAddressActivity.class);
				startActivity(intent);
				break;
			default:
				break;
			}
		}
	};
	

	@Override
	public void onPostSuccess(int postId, String msg) {
		super.onPostSuccess(postId, msg);
		Gson gson = new Gson();
		Type type = null;
		switch (postId) {
		case GET_ADDRESS_LIST:
			type = new TypeToken<DtoInfo<Address>>() {
			}.getType();
			DtoInfo<Address> data = gson.fromJson(msg, type);
			datas.clear();
			datas.addAll(data.data.records);
			mJfMallAddressAdapter.notifyDataSetChanged();
			addressList.setVisibility(View.VISIBLE);
			break;
		case SET_DEFAULT_ADDESS:
			type = new TypeToken<DtoInfoNoPage<Info>>() {
			}.getType();
			DtoInfoNoPage<Info> dto = gson.fromJson(msg, type);
			String suc = String.valueOf(dto.suc);
			if (suc != null && "1011".equals(suc.trim())) {
				MyToast.showHMToast(JfMallAdresActivity.this, true, "设置成功");
			}
			onRequest(GET_ADDRESS_LIST, UrlConstant.ADDRESSLIST,
					HttpMethod.GET, null); // 设为默认地址后，重新获取数据
			defaultAddress = null;
			break;
		case DELETE_ADDRESSS:
			type = new TypeToken<DtoInfoNoPage<String>>() {
			}.getType();
			DtoInfoNoPage<String> dto2 = gson.fromJson(msg, type);
			String suc2 = String.valueOf(dto2.suc);
			if (suc2 != null && "1011".equals(suc2.trim())) {
				MyToast.showHMToast(JfMallAdresActivity.this, true, "删除成功");
				if (!TextUtils.isEmpty(deleteId)) {
					Address defaultAddress = getDefaultAddress();
					if (defaultAddress != null && defaultAddress.id != null
							&& getDefaultAddress().id.equals(deleteId)) {
						editor.putString("address", "");
						editor.commit();
					}
				}
			}
			break;
		default:
			break;
		}
		
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		super.onPostSuccess(postId, msg);
		switch (postId) {
		case GET_ADDRESS_LIST:
			MyToast.showHMToast(JfMallAdresActivity.this, false, "获取地址信息失败");
			break;
		default:
			break;
		}
	}

	@Override
	protected void setParams() {
		footView = (LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.view_jfmall_address_add_foot, null);
		footView.setId(ADDRESS_ADD_VIEW_ID);
		footView.setOnClickListener(clickListener);
		if (datas == null) {
			datas = new ArrayList<Address>();
		}
		home_title_txt.setText("地址管理");
		address_title.setOnTouchListener(touch);
		adapterNetRequest = new AdapterNetRequest() {

			@Override
			public void defaultNetRequest(String itemId) {
				RequestParams params = new RequestParams();
				params.addBodyParameter("itemId", itemId);
				for (Address address : datas) {
					if (address.id.equals(itemId)) {
						defaultAddress = address;
					}
				}
				if (defaultAddress != null) {
					addToDefaultAddress(defaultAddress);
				}
				onRequest(SET_DEFAULT_ADDESS, UrlConstant.SET_DEFAULT_ADDESS,
						HttpMethod.POST, params);
			}

			@Override
			public void deleteAddress(String itemId) {
				RequestParams params = new RequestParams();
				params.addBodyParameter("itemId", itemId);
				onRequest(DELETE_ADDRESSS, UrlConstant.DELETE_ADDRESS,
						HttpMethod.POST, params);
				deleteId = itemId;
			}
		};
		starter = this.getIntent().getIntExtra("starter", 0);
		getXList().addFooterView(footView);
		getXList().setPullRefreshEnable(true);
		getXList().setPullLoadEnable(false); // 禁止加载更多
		getXList().setAutoLoadEnable(false); // 禁止自动加载
		getXList().setEnabled(true);
		mJfMallAddressAdapter = new JfMallAddressAdapter(
				getApplicationContext(), datas, adapterNetRequest);
		getXList().setAdapter(mJfMallAddressAdapter);
		getXList().setOnItemClickListener(this);
		getXList().setXListViewListener(this);
		onRequest(GET_ADDRESS_LIST, UrlConstant.ADDRESSLIST, HttpMethod.GET,
				null);
		sharedPreferences = getSharedPreferences("test", Activity.MODE_PRIVATE);
		editor = sharedPreferences.edit();
		
		
	}
	
	OnItemClickListener itemclicklistener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Address address = datas.get(position);
			Intent intent = new Intent();
			if (starter == IS_FROM_SHOP_CART) { // 选择默认地址
				intent.setClass(JfMallAdresActivity.this,
						JfMallShopCartActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("address", address);
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				AppBasic.getInstance().finishActivity(JfMallAdresActivity.this);

			} else { // 编辑修改地址
				intent.setClass(JfMallAdresActivity.this,
						JfMallAddNewAddressActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("address", address);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		}
	};

	/**
	 * 设为默认地址，存储到本地
	 * 
	 * @param address
	 */
	public void addToDefaultAddress(Address address) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(baos);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			oos.writeObject(address);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String myDefaultaddress = new String(Base64.encode(baos.toByteArray(),
				Base64.DEFAULT));
		try {
			oos.close();
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		editor.putString("address", myDefaultaddress);
		editor.commit();
	}

	@Override
	protected void onResume() {
		onRequest(GET_ADDRESS_LIST, UrlConstant.ADDRESSLIST, HttpMethod.GET,
				null);
		super.onResume();
	};

	@Override
	public void onRefresh() {
		super.onRefresh();
		onRequest(GET_ADDRESS_LIST, UrlConstant.ADDRESSLIST, HttpMethod.GET,
				null);
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishActivity(JfMallAdresActivity.this);
	}

	@Override
	protected void rightButton() {

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Address address = datas.get(position - 1);
		Intent intent = new Intent();
		if (starter == IS_FROM_SHOP_CART) { // 选择默认地址
			intent.setClass(JfMallAdresActivity.this,
					JfMallShopCartActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("address", address);
			intent.putExtras(bundle);
			setResult(RESULT_OK, intent);
			AppBasic.getInstance().finishActivity(JfMallAdresActivity.this);
			addToDefaultAddress(address);
		} else { // 编辑修改地址
			intent.setClass(JfMallAdresActivity.this,
					JfMallAddNewAddressActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("address", address);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}

	public Address getDefaultAddress() {
		String defaultAddress = sharedPreferences.getString("address", "");
		Address mdefaultAddress = new Address();
		if (!defaultAddress.equals("")) {
			byte[] addressBytes = Base64.decode(defaultAddress.getBytes(),
					Base64.DEFAULT);
			ByteArrayInputStream bais = new ByteArrayInputStream(addressBytes);
			try {
				ObjectInputStream bis = new ObjectInputStream(bais);
				try {
					mdefaultAddress = (Address) bis.readObject();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} finally {
					bis.close();
				}
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return mdefaultAddress;
	}
}
